package com.link2room.bumblebee.facade.impl;

import com.link2room.bumblebee.constant.SysNoConstant;
import com.link2room.bumblebee.dto.param.base.SysNoBaseParamDto;
import com.link2room.bumblebee.exception.BumblebeeException;
import com.link2room.bumblebee.facade.ISysNoFacadeService;
import com.link2room.common.service.ICommonService;
import com.link2room.common.util.SpringUtil;
import com.link2room.enums.exception.BumblebeeSysExceptionEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author sqj88
 * @date 2018/1/22 14:31
 */
@Component("sysNoFacadeService")
public class SysNoFacadeServiceImpl implements ISysNoFacadeService {

    @Resource
    private ICommonService commonService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public String getNo(SysNoBaseParamDto sysNoBaseParamDto) throws Exception {
        String key=sysNoBaseParamDto.getNoType();
        RedisLockRegistry redisLockRegistry= Optional.ofNullable(SysNoConstant.map.get(key)).orElse( new RedisLockRegistry(redisTemplate.getConnectionFactory(),key));
        Lock lock=redisLockRegistry.obtain(key);
        if(lock.tryLock(5, TimeUnit.SECONDS)){
            try {
                List params= Stream.of(key).collect(Collectors.toList());
                commonService=Optional.ofNullable(commonService).orElse((ICommonService) SpringUtil.getBean("commonServiceSupport"));
                return commonService.findOneFieldByProcedure("create_No",params);
            }finally {
                lock.unlock();
            }
        }else {
            throw new BumblebeeException(BumblebeeSysExceptionEnum.GENERATE_NEW_NO_ERROR,key);
        }
    }
}
